<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button class="btn">创建100000个div</button>

<script>
    const btn = document.querySelector('.btn')
    const datas = Array.from({length: 100000}, (_, i) => i)

    btn.onclick = () => {
        const taskHandler = (_, i) => {
            const div = document.createElement('div')
            div.textContent = i
            document.body.appendChild(div)
        }

        const scheduler = (task) => {
            setTimeout(() => {
                const start = Date.now()
                task(() => Date.now() - start < 100)
            }, 100)
        }
        browserPerformChunk(100000, taskHandler)
    }

    function performChunk(datas, taskHandler, scheduler) {
        if (typeof datas === 'number') {
            datas = {length: datas}
        }

        if (datas.length === 0) return
        let i = 0

        function _run() {
            scheduler((isGo) => {
                while (isGo() && i < datas.length) {
                    taskHandler(datas[i], i)
                    ++i
                }
                _run()
            })
        }

        _run()
    }

    function browserPerformChunk(datas, taskHandler) {
        const scheduler = (task) => {
            requestIdleCallback((deadline) => {
                task(() => deadline.timeRemaining() > 0)
            })
        }
        performChunk(datas, taskHandler, scheduler)
    }
</script>
</body>
</html>